﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StudentList.aspx.cs" Inherits="NX5Web.admin.StudentData.StudentList" %>



<div id="subApp" style="margin:15px;">  
    <el-dialog
  v-model="dialogVisible"
  title="添加"
  width="500" 
>
  <div>
      <el-form  ref="form" :model="form" :rules="rules"  label-width="auto" style="max-width: 600px">  
          <el-form-item label="姓名" prop="StudentName">
            <el-input  v-model="form.StudentName"/>
          </el-form-item> 
          <el-form-item label="电话" prop="Phone">
            <el-input v-model="form.Phone"/>
          </el-form-item>
          <el-form-item label="学科" prop="SubjectId">
              <el-select
                  v-model="form.SubjectId"
                  multiple
                  placeholder="开通学科"
                >
                  <el-option
                    v-for="item in SubjectList"
                    :key="item.ID"
                    :label="item.Title"
                    :value="item.ID"
                  ></el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="配书" prop="BookId" v-if="mode=='new'"> 
              <el-cascader v-model="form.BookId" :options="BookList" style="width:100%;"/> 
          </el-form-item>   
          <el-form-item label="分配教练" prop="DefaultTeacherId">  
               <el-cascader v-model="form.DefaultTeacherId" :options="TeacherList" style="width:100%;"/> 
          </el-form-item> 
           <el-form-item label="分配账号" prop="UserName" v-if="mode=='new'">
             <el-input v-model="form.UserName" />
          </el-form-item>  
         <el-form-item label="有效期" prop="Period"> 
           <el-date-picker v-model="form.Period" type="date"></el-date-picker>
        </el-form-item>  
          <el-form-item label="常规课量" prop="RemeberLicence" v-if="mode=='new'">
    <el-input-number v-model="form.RemeberLicence" :min="1"/>
  </el-form-item>  
  <el-form-item label="保温课量" prop="ReviewLicence" v-if="mode=='new'">
    <el-input-number v-model="form.ReviewLicence" :min="1"/>
  </el-form-item> 
      </el-form>
  </div>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="AddStudent()">
        确 定
      </el-button>
    </div>
  </template>
</el-dialog>
     
    <el-dialog
  v-model="bookdia"
  title="配书"
  width="500" 
>
  <div>
      <el-form  ref="form" :model="form" :rules="rules"  label-width="auto" style="max-width: 600px">   
          <el-form-item label="配书"> 
              <el-cascader v-model="BookId" :options="StudentBookList" style="width:100%;"/> 
          </el-form-item>    
      </el-form>
  </div>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="bookdia = false">取 消</el-button>
      <el-button type="primary" @click="AssignBook()">
        确 定
      </el-button>
    </div>
  </template>
</el-dialog>


        <el-dialog
          v-model="showlicence"
          title="授权明细"
          width="600" 
        >
            <div>
                <el-form label-width="auto" style="max-width: 600px"> 
                     
                    <el-form-item label="常规课量" prop="StudentName">
                      <el-input-number v-model="RemeberLicence" :min="1"/>
                    </el-form-item>  
                    <el-form-item label="保温课量" prop="StudentName">
                      <el-input-number v-model="ReviewLicence" :min="1"/>
                    </el-form-item>  
                </el-form>
            </div>
            <div>
                <el-table :data="LicenceListData" style="width: 100%">
                    <el-table-column label="购买时间" width="180" >
                      <template #default="scope">{{ scope.row.Created }}</template>
                    </el-table-column> 
                    <el-table-column label="常规课量" width="90" >
                        <template #default="scope">{{ scope.row.RemeberLicence }}节</template>
                    </el-table-column> 
                    <el-table-column label="保温课量" width="90" >
                        <template #default="scope">{{ scope.row.ReviewLicence }}节</template>
                    </el-table-column> 
                    <el-table-column label="说明">
                      <template #default="scope">{{ scope.row.Description }}</template>
                    </el-table-column> 
                </el-table>
            </div>
            <div style="margin-top:10px;">
                <el-pagination
                  v-model:current-page="SLice.pageIndex"
                  v-model:page-size="SLice.pageSize"
                  :page-sizes="[10, 20, 30, 40]"
                  layout="total, prev, pager, next"
                  :total="SLice.totalCount"
                  @size-change="LICpageSizeChange"
                  @current-change="LICpageNumberChange"
                />
            </div>
            <template #footer>
                <div class="dialog-footer">
                <el-button @click="showlicence = false">取 消</el-button>
                <el-button type="primary" @click="AddLicence()">
                    确 定
                </el-button>
                </div>
            </template>
            </el-dialog>


    <div style="    width: 100%;border-bottom: 1px solid #eee;padding-bottom: 5px;">
        <el-button type="primary" @click="showAddDia()">添 加</el-button>   
        <%--<el-button type="primary" @click="showAddDia()">批量导入</el-button> 
        <el-button type="primary" @click="showAddDia()">导 出</el-button> --%>
    </div>
        <div style="margin-top:10px;">
            <el-form :inline="true" :model="filterform" ref="filterform"> 
                <el-form-item label="姓名" prop="Name">
                    <el-input v-model="filterform.Name" placeholder="请输入姓名"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="Phone">
                    <el-input v-model="filterform.Phone" placeholder="请输入电话"></el-input>
                </el-form-item>
                <el-form-item label="初始阶段" prop="Lv">
                     <el-select v-model="filterform.Lv" style="width:100px;">
                            <el-option label="学龄前" value="1"></el-option> 
                            <el-option label="小学" value="2"></el-option> 
                            <el-option label="初中" value="3"></el-option> 
                            <el-option label="高中" value="4"></el-option> 
                            <el-option label="大学" value="5"></el-option> 
                            <el-option label="成人" value="6"></el-option> 
                            <el-option label="其他" value="7"></el-option>  
                     </el-select>
                </el-form-item> 
                <el-form-item label="教练" prop="Teacher" style="width:400px">   
                     <el-cascader v-model="filterform.Teacher" :options="TeacherList" style="width:100%;"/> 
                </el-form-item>
                 <el-form-item>
                  <el-button type="primary" @click="resetFilter">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
    <div>
        <el-table :data="tableData" style="width: 100%">
           <%--<el-table-column type="selection" width="55" ></el-table-column>--%>
           <el-table-column label="姓名" width="120" >
             <template #default="scope">{{ scope.row.StudentName }}</template>
           </el-table-column> 
            <el-table-column label="阶段" width="120" >
              <template #default="scope">{{ scope.row.BaseLv }}</template>
            </el-table-column> 
            
             <el-table-column label="电话 / 账号">
               <template #default="scope">{{ scope.row.Phone == scope.row.UserName?protphone(scope.row.UserName):(protphone(scope.row.Phone)+' / '+protphone(scope.row.UserName)) }}</template>  
             </el-table-column> 
            <el-table-column label="教练">
              <template #default="scope">{{ scope.row.TeacherName }}</template>
            </el-table-column>  
            <el-table-column label="余量(常规/保温)">
              <template #default="scope">{{ scope.row.RemeberLicence-scope.row.UsedRemember }}/{{ scope.row.ReviewLicence-scope.row.UsedReview }}</template>
            </el-table-column>
            <el-table-column label="有效期">
              <template #default="scope">{{ dateFormat(scope.row.Period) }}</template>
            </el-table-column>
            <%--<el-table-column label="创建日期">
              <template #default="scope">{{ dateFormat(scope.row.Created) }}</template>
            </el-table-column>--%>
           <el-table-column label="" width="260">
              <template #default="scope">
                <el-button v-if="scope.row.Valid" size="small" @click="handleEdit(scope.$index, scope.row)">
                  编辑
                </el-button>
                <el-button v-if="scope.row.Valid" size="small" @click="handleAssgin(scope.$index, scope.row)">
                  配书
                </el-button>
                <el-button v-if="scope.row.Valid" size="small" @click="bylicence(scope.$index, scope.row)">
                  购买
                </el-button>
                <el-button v-if="scope.row.Valid"
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                >
                  停用
                </el-button>

                  <el-button v-if="!scope.row.Valid"
              size="small"
              type="danger"
              @click="handleReset(scope.$index, scope.row)"
            >
              启用
            </el-button>
              </template>
            </el-table-column>
        </el-table>

        <div style="margin-top:10px;">
            <el-pagination
              v-model:current-page="pageIndex"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 30, 40]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              @size-change="pageSizeChange"
              @current-change="pageNumberChange"
            />
        </div>
    </div> 
</div>
<script>
    var subApp = createApp({
        el: '#subApp',
        data() {
            return {
                form: {
                    //CompanyId: null,
                    StudentName: "",
                    Phone: "",
                    UserName: "",
                    Period: "",
                    RemeberLicence: 0,
                    ReviewLicence: 0,
                    DefaultTeacherId: null,
                    SubjectId: [],
                    BookId: null
                },
                filterform: {
                    Name:null,
                    Lv: null,
                    Phone:null,
                    Teacher:null
                },
                SubjectList: [],
                rules: {
                    //CompanyId: [
                    //    { required: true, message: '', trigger: 'change' }
                    //],
                    DefaultTeacherId: [
                        { required: true, message: '', trigger: 'change' }
                    ],
                    BookId: [
                        { required: true, message: '', trigger: 'change' }
                    ],
                    StudentName: [
                        { required: true, message: '', trigger: 'blur' },
                        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                    ],
                    SubjectId: [
                        { required: true, message: '', trigger: 'change' }
                    ],
                    Phone: [
                        { required: true, message: '', trigger: 'blur' },
                        { min: 11, max: 11, message: '无效电话', trigger: 'blur' }
                    ],
                    UserName: [
                        { required: true, message: '', trigger: 'blur' },
                        { min: 11, max: 11, message: '请输入11位手机号', trigger: 'blur' }
                    ],
                    Period: [
                        { type: 'date', required: true, message: '', trigger: 'blur' }
                    ],
                },
                dialogVisible: false,
                showlicence:false,
                StudentList: [],
                CompanyList: [],
                TeacherList: [],
                BookList:[],
                LicenceList: [],
                CompanyInfo: {},
                RemeberLicence: 0,
                ReviewLicence: 0,
                mode:'new',
                ActiveItem: null,
                totalCount: 0,
                pageIndex: 1,
                pageSize: 10,
                BookId: null,
                StudentBookList:[],
                bookdia:false,
                SLice: {
                    totalCount: 0,
                    pageIndex: 1,
                    pageSize: 10,
                }
            };
        },
        computed: { 
            LicenceListData() {
                var temp = this.LicenceList.filter(x => {
                    return true;
                });

                this.SLice.totalCount = temp.length;

                return temp.slice((this.SLice.pageIndex - 1) * this.SLice.pageSize,
                    this.SLice.pageIndex * this.SLice.pageSize);
            },
            tableData() {
                var temp = this.StudentList.filter(x => {
                    return (
                        (this.filterform.Name == null || x.StudentName.indexOf(this.filterform.Name) != -1)
                        && (this.filterform.Phone == null || x.Phone.indexOf(this.filterform.Phone) != -1) 
                        && (this.filterform.Lv == null || x.BaseLvId == this.filterform.Lv)
                        && (this.filterform.Teacher == null || x.DefaultTeacherId == this.filterform.Teacher[1])
                    );
                });
                this.totalCount = temp.length;

                return temp.slice((this.pageIndex - 1) * this.pageSize, this.pageIndex * this.pageSize);
            }
        },
        methods: {
            resetFilter() {
                this.$refs.filterform.resetFields()
            },
            LICpageNumberChange(pageIndex) {
                this.SLice.pageIndex = pageIndex;
            },
            LICpageSizeChange(pageSize) {
                this.SLice.pageIndex = 1;
                this.SLice.pageSize = pageSize;
            },
            pageNumberChange(pageIndex) {
                this.pageIndex = pageIndex;
            },
            pageSizeChange(pageSize) {
                this.pageIndex = 1;
                this.pageSize = pageSize;
            },
            protphone(phone) {
                var user = new ktluser();
                if (user.hasRole(1) || user.hasRole(6)) {
                    return phone;
                } else {
                    return phone.replace(/(\d{3})\d*(\d{4})/, "$1****$2");
                } 
            },
            AddLicence() {
                loaddingPlus(true);
                ktlapi({
                    "action": "Cus_AddLicence",
                    "data": {
                        "StudentAccountId": this.ActiveItem.AccountId,
                        "Rember": this.RemeberLicence,
                        "Review": this.ReviewLicence
                    }
                }).then(res => {
                    if (res.data[0]["code"] == 0) {
                        MsgBox.error(res.data[0]["err"]);
                        return;
                    }
                    this.ActiveItem["RemeberLicence"] += this.ReviewLicence;
                    this.ActiveItem["ReviewLicence"] += this.ReviewLicence;
                    this.showlicence = false;
                    loaddingPlus(false);
                });
            },
            bylicence(index, row) {
                console.log(row);
                this.ActiveItem = row;
                loaddingPlus(true);
                ktlapi({
                    "action": "Cus_GetLicence",
                    "data": {
                        "StudentAccountId": this.ActiveItem.AccountId, 
                    }
                }).then(res => { 
                    this.LicenceList = res.data;
                    loaddingPlus(false);
                    this.showlicence = true;
                }); 
            },
            isValidPhoneNumber(phoneNumber) {
                // 中国大陆手机号（简化）
                const chinaRegex = /^1[3-9]\d{9}$/;
                // 美国手机号（简化）
                const usRegex = /^(\+?1\s?)?(\d{3})[-.]?(\d{3})[-.]?(\d{4})$/;
                // 英国手机号（简化）
                const ukRegex = /^(\+?44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/;

                return chinaRegex.test(phoneNumber) || usRegex.test(phoneNumber) || ukRegex.test(phoneNumber);
            },
            AddStudent() {
                const that = this;
                this.$refs.form.validate((valid, fields) => {
                    if (valid) {
                        var proc = 'Cus_AddStudent';
                        var data = {};
                        if (this.mode == 'new') {
                            if (!that.isValidPhoneNumber(that.form.Phone) || !that.isValidPhoneNumber(that.form.UserName)) {
                                MsgBox("手机号无效");
                                return;
                            }
                            
                            proc = 'Cus_AddStudent2';
                            data = {
                                "CompanyId": new ktluser().userInfo().CompanyId,
                                "StudentName": that.form.StudentName,
                                "Phone": that.form.Phone,
                                "UserName": that.form.UserName,
                                "Rember": that.form.RemeberLicence,
                                "Review": that.form.ReviewLicence,
                                "DefaultTeacherId": typeof (that.form.DefaultTeacherId) == 'number' ? that.form.DefaultTeacherId : that.form.DefaultTeacherId[1],
                                "Period": dateFormat(that.form.Period),
                                "BookId": that.form.BookId[2],
                                "SubjectId": that.form.SubjectId.join(',')
                            }
                        } else {
                            if (!that.isValidPhoneNumber(that.form.Phone)) {
                                MsgBox("手机号无效");
                                return;
                            }
                            proc = 'Cus_EditStudent2';
                            data = {
                                "ID": that.ActiveItem.ID,
                                "StudentName": that.form.StudentName,
                                "SubjectId": that.form.SubjectId.join(','),
                                "Phone": that.form.Phone, 
                                "DefaultTeacherId": typeof (that.form.DefaultTeacherId) == 'number' ? that.form.DefaultTeacherId : that.form.DefaultTeacherId[1],
                                "Period": dateFormat(that.form.Period) 
                            }
                        }

                        loaddingPlus(true);
                        ktlapi({
                            "action": proc,
                            "data": data
                        }).then(res => {
                            if (this.mode == 'new') {
                                if (res.data[0]["code"] == 0) {
                                    MsgBox.error(res.data[0]["err"]);
                                    return;
                                } 
                            }
                            that.loadStudent();
                            that.dialogVisible = false;
                            that.$refs.form.resetFields()
                            loaddingPlus(false);
                        });
                    }
                }); 
            },
            handleAssgin(index, row) { 
                this.ActiveItem = row;
                loaddingPlus(true);
                ktlapi({
                    "action": "Cus_StudentBooks",
                    "data": {
                        "StudentId": this.ActiveItem.ID,
                    }
                }).then(res => {

                    this.StudentBookList = res.data;

                    this.StudentBookList = pivotJson(this.StudentBookList, "Title", ["BookId", "BookName", "GroupName", "Title", "UseGrade", "Valid"]);

                    for (var i = 0; i < this.StudentBookList.length; i++) {
                        this.StudentBookList[i]["value"] = this.StudentBookList[i]["BookId"];
                        this.StudentBookList[i]["label"] = this.StudentBookList[i]["Title"];
                        this.StudentBookList[i]["items"] = pivotJson(this.StudentBookList[i]["items"], "GroupName", ["BookId", "BookName", "GroupName", "Title", "UseGrade", "Valid"]);
                        this.StudentBookList[i]["children"] = this.StudentBookList[i]["items"];

                        for (var j = 0; j < this.StudentBookList[i]["children"].length; j++) {
                            this.StudentBookList[i]["children"][j]["value"] = this.StudentBookList[i]["children"][j]["BookId"];
                            this.StudentBookList[i]["children"][j]["label"] = this.StudentBookList[i]["children"][j]["GroupName"];
                            this.StudentBookList[i]["children"][j]["children"] = this.StudentBookList[i]["children"][j]["items"];

                            for (var k = 0; k < this.StudentBookList[i]["children"][j]["children"].length; k++) {
                                this.StudentBookList[i]["children"][j]["children"][k]["value"] = this.StudentBookList[i]["children"][j]["children"][k]["BookId"];
                                this.StudentBookList[i]["children"][j]["children"][k]["label"] = this.StudentBookList[i]["children"][j]["children"][k]["BookName"]
                            }
                        }

                    } 
                    loaddingPlus(false);
                    this.bookdia = true;
                }); 
            },
            AssignBook() { 
                if (this.BookId == null) {
                    return;
                }
                loaddingPlus(true);
                ktlapi({
                    "action": "Cus_SetStudentNewBook",
                    "data": {
                        StudentId: this.ActiveItem.ID,
                        BookId: this.BookId[2]
                    }
                }).then(res => { 
                    loaddingPlus(false);
                    MsgBox("分配完成");
                    this.BookId = null;
                    this.bookdia = false;
                });
            },
            handleEdit(index, row) {
                this.ActiveItem = row;
                this.mode = 'edit';

                this.form.StudentName = this.ActiveItem["StudentName"];
                this.form.Phone = this.ActiveItem["Phone"]; 
                this.form.RemeberLicence = this.ActiveItem["RemeberLicence"];
                this.form.ReviewLicence = this.ActiveItem["ReviewLicence"];
                this.form.DefaultTeacherId = this.ActiveItem["DefaultTeacherId"];
                this.form.Period = this.ActiveItem["Period"];
                this.form.Lv = this.ActiveItem["BaseLvId"].toString();


                this.dialogVisible = true; 
            },
            handleReset(index, row) {
                if (window.confirm("是否启用该条目?")) {
                    loaddingPlus(true);
                    ktlapi({
                        "action": "Cus_ResetStudent",
                        "data": {
                            "ID": row.ID
                        }
                    }).then(res => {
                        row.Valid = true;

                        loaddingPlus(false);
                    });
                }
            },
            handleDelete(index, row) {
                console.log(index, row)
                if (window.confirm("是否停用该条目?")) {
                    loaddingPlus(true);
                    ktlapi({
                        "action": "Cus_DeleteStudent",
                        "data": {
                            "ID": row.ID
                        }
                    }).then(res => {
                        row.Valid = false;

                        loaddingPlus(false);
                    });
                }
            },
            showAddDia() {  
                this.mode = 'new';
                //loaddingPlus(true);
                //ktlapi({
                //    "apiurl": OT.CommandSet,
                //    "action": "Cus_GetCompanyAndTeacherList",
                //    "data": {}
                //}).then(res => {
                //    this.TeacherList = res.data.tables[0].table;

                //    this.TeacherList = pivotJson(this.TeacherList, "CompanyId", ["CompanyId", "CompanyName"]);
                //    for (var i = 0; i < this.TeacherList.length; i++) {
                //        this.TeacherList[i]["value"] = this.TeacherList[i]["CompanyId"];
                //        this.TeacherList[i]["label"] = this.TeacherList[i]["CompanyName"];
                //        this.TeacherList[i]["children"] = this.TeacherList[i]["items"];
                //    }
                //    console.log(this.TeacherList);


                //    loaddingPlus(false);
                //    this.dialogVisible = true;
                //}); 
                this.dialogVisible = true; 
            },
            loadStudent() {
                loaddingPlus(true);
                var user = new ktluser();
                ktlapi({
                    "apiurl": OT.CommandSet,
                    "action": "Cus_GetCompanyStudentList",
                    "data": {
                        CompanyId: user.userInfo().CompanyId
                    }
                }).then(res => {
                    this.CompanyInfo = res.data.tables[0].table[0];
                    this.StudentList = res.data.tables[1].table;
                    loaddingPlus(false);
                    loaddingPlus(true);
                    ktlapi({
                        "apiurl": OT.CommandSet,
                        "action": "Cus_GetCompanyAndTeacherList",
                        "data": {}
                    }).then(res => {
                        this.TeacherList = res.data.tables[0].table;
                        this.BookList = res.data.tables[1].table;
                         
                        this.BookList = pivotJson(this.BookList, "Title", ["BookId", "BookName", "GroupName", "Title", "UseGrade", "Valid"]);

                        for (var i = 0; i < this.BookList.length; i++) {
                            this.BookList[i]["value"] = this.BookList[i]["BookId"];
                            this.BookList[i]["label"] = this.BookList[i]["Title"]; 
                            this.BookList[i]["items"] = pivotJson(this.BookList[i]["items"], "GroupName", ["BookId", "BookName", "GroupName", "Title", "UseGrade", "Valid"]);
                            this.BookList[i]["children"] = this.BookList[i]["items"];

                            for (var j = 0; j < this.BookList[i]["children"].length; j++) {
                                this.BookList[i]["children"][j]["value"] = this.BookList[i]["children"][j]["BookId"];
                                this.BookList[i]["children"][j]["label"] = this.BookList[i]["children"][j]["GroupName"];
                                this.BookList[i]["children"][j]["children"] = this.BookList[i]["children"][j]["items"];

                                for (var k = 0; k < this.BookList[i]["children"][j]["children"].length; k++) {
                                    this.BookList[i]["children"][j]["children"][k]["value"] = this.BookList[i]["children"][j]["children"][k]["BookId"];
                                    this.BookList[i]["children"][j]["children"][k]["label"] = this.BookList[i]["children"][j]["children"][k]["BookName"]
                                }
                            }

                        }

                        this.TeacherList = pivotJson(this.TeacherList, "CompanyId", ["CompanyId", "CompanyName"]);
                        for (var i = 0; i < this.TeacherList.length; i++) {
                            this.TeacherList[i]["value"] = this.TeacherList[i]["CompanyId"];
                            this.TeacherList[i]["label"] = this.TeacherList[i]["CompanyName"];
                            this.TeacherList[i]["children"] = this.TeacherList[i]["items"];
                        }
                        loaddingPlus(false);
                    });  
                });
            },
            loadSubject() {
                ktlapi({
                    action: 'Cus_GetAllSubjectList',
                }).then(resp => {
                    this.SubjectList = resp.data || [];
                })
            },
            init() {
                this.loadStudent();
                this.loadSubject();
            }
        },
        mounted: function () {
            this.init();
        }
    });
</script>